<template>
  <!-- 以下是题目内容 -->
  <div class="questionInfo-container">
    <div class="question-info">
      <span>【{{ questionInfo.questionTypeName + '题型' }}】</span>
      <span style="color: #909399">
        ({{ questionType == 2 ? '多选题' : '单选题' }}) [ {{ questionMarks.index + 1 }} ]</span
      >
    </div>
    <!-- 属于B型题 -->
    <!-- <template v-if="questionType === isB">
      题目问题 & 选项
      <div class="is-b">
        <div v-for="(questionItem, questionIndex) in question" :key="questionItem.questionId" class="single-question">
          {{ questionItem }}
          <div class="question-title">{{ questionIndex + 1 }}. {{ questionItem.questionContent }}</div>
          <div>
            <span
              v-for="(answerItem, answerIndex) in questionItem.answer"
              :key="answerItem.id"
              class="question-options"
              :class="answerIndex == bTypeAnswer[questionIndex] ? 'is-select' : ''"
              @click="selectAnswer(questionIndex, answerIndex)">
              {{ LETTER[answerIndex] }}
            </span>
          </div>
        </div>
        答案选项
        <div v-for="answerItem in question[0].answer" :key="answerItem.id" class="answer-options">
          {{ answerItem.answer }}
        </div>
      </div>
      <div v-if="readOnly && bTypeAnswer.length === 0" class="noAnswer">未作答</div>
    </template> -->
    <!-- 属于x型题或其他单选题 -->
    <template>
      <!-- 题目问题 -->
      <div class="question-title">{{ questionInfo.questionContent }}</div>
      <!-- 题目材料 -->
      <div class="question-materials">
        <span v-for="(item, index) in questionInfo.images" :key="index">
          <el-image style="width: 150px; margin-right: 5px" :src="item" :preview-src-list="questionInfo.images" />
        </span>
      </div>
      <!-- 题目答案 -->
      <div class="question-answers">
        <!-- 属于多选题型题 -->
        <template v-if="questionType === 2">
          <el-checkbox-group v-model="checkboxAnswer">
            <el-checkbox
              v-for="item in questionInfo.answer"
              :key="item.id"
              :label="item"
              :disabled="questionInfo.isLocked || readOnly"
              class="answer-item"
              :class="result !== null && readOnly ? (result ? 'isRight' : 'isWrong') : ''"
              @change="changeAnswer">
              <div class="answer-content">
                <template v-if="item.images">
                  <div class="answer-img">
                    <img
                      v-for="(innerItem, innerIndex) in item.images"
                      :key="innerIndex"
                      :src="baseImgUrl + innerItem"
                      alt="获取图片失败" />
                  </div>
                </template>
                <div class="answer-text">{{ item.answer }}</div>
              </div>
            </el-checkbox>
          </el-checkbox-group>
          <div v-if="readOnly && checkboxAnswer.length === 0" class="noAnswer">未作答</div>
        </template>
        <!-- 不属于多选题型题 -->
        <template v-else>
          <el-radio
            v-for="item in questionInfo.answer"
            :key="item.id"
            v-model="radioAnswer"
            :label="item"
            :disabled="questionInfo.isLocked || readOnly"
            class="answer-item"
            :class="result !== null && readOnly ? (result ? 'isRight' : 'isWrong') : ''"
            @change="changeAnswer">
            <!-- {{ item.images.length }} -->
            <div class="answer-content">
              <template v-if="item.images">
                <div class="answer-img">
                  <img
                    v-for="(innerItem, innerIndex) in item.images"
                    :key="innerIndex"
                    :src="baseImgUrl + innerItem"
                    alt="获取图片失败" />
                </div>
              </template>
              <div class="answer-text">{{ item.answer }}</div>
            </div>
          </el-radio>
          <div v-if="readOnly && radioAnswer === null" class="noAnswer">未作答</div>
        </template>
      </div>
    </template>

    <!-- 在查阅试卷的时候才显示 -->
    <template v-if="readOnly">
      <!-- 操作按钮 -->
      <div class="btns">
        <div class="result">
          <template v-if="result">
            <span style="color: #67c23a"><i class="el-icon-success" /> 回答正确</span>
          </template>
          <template v-else>
            <span style="color: #f56c6c"><i class="el-icon-error" /> 回答错误</span>
          </template>
          <span class="analysis-btn" @click="showAnalysis">{{ analysisVisible ? '收起解析' : '查看解析' }}</span>
        </div>
      </div>

      <!-- 显示解析 -->
      <div v-if="analysisVisible" class="show-answer">
        <div class="true-answer">
          <span>正确答案: {{ trueAnswer || '无' }}</span>
        </div>
        <div class="analysis">解析: {{ questionInfo.analysis || '这道题还没有解析喔~' }}</div>
      </div>
    </template>
    <div class="statusBox">
      <el-button type="success" @click="handleChange">修改</el-button>
      <el-button type="danger" @click="handleSave">保存</el-button>
    </div>
  </div>
</template>
<script>
export default {
  name: 'Question',
  filters: {
    // questionTypeFilter(id) {
    //   const questionType = {
    //     1: 'A1型题',
    //     2: 'X型题',
    //     3: 'A3/4型题',
    //     4: 'B型题',
    //     5: 'A2型题',
    //   }
    //   return questionType[id]
    // },
  },
  props: {
    questionInfo: {
      type: [Object, Array],
      default() {
        return {}
      },
      required: true,
    },
    questionMark: {
      type: Object,
      default() {
        return {}
      },
      required: true,
    },
    readOnly: {
      type: Boolean,
      default: false,
    },
    // isLocked: {
    //   type: Boolean,
    //   default: false,
    // },
  },

  data() {
    return {
      LETTER: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'], // 选项前缀
      questionType: this.questionInfo.questionType || 4, // 题目类型
      question: this.questionInfo, // 题目信息
      questionMarks: this.questionMark, // 题目做过的痕迹
      questionStatus: this.questionInfo.status, // 题目是否做过的状态
      radioAnswer: null, // 单选题的答案
      checkboxAnswer: [], // 多选题的答案
      bTypeAnswer: [], // B型题答案

      result: null, // 结果
      trueAnswer: '', // 正确答案
      analysisVisible: false, // 显示解析
      isB: 4, // B型题
      isX: 2, // X型题
      baseImgUrl: '',
    }
  },
  watch: {
    // 更新数据
    questionInfo(newVal, oldVal) {
      // console.log(newVal, oldVal, 'newVal', 'oldVaL')
      const QuestionListStore = this.$store.getters.questionList
      const index = QuestionListStore.findIndex((item) => item.questionId === oldVal.questionId)
      // 如果上一道题修改了但是没有保存，自动保存
      if (index !== -1) {
        console.log(oldVal, 'oldVal')
        if (oldVal.isAnswer) {
          oldVal.isLocked = true
        } else {
          oldVal.isLocked = false
        }
        this.$store.commit('question/SET_QUESTION', oldVal)
      } else {
        if (oldVal.isAnswer) {
          oldVal.isLocked = true
        } else {
          oldVal.isLocked = false
        }
        this.$store.commit('question/SET_QUESTION', oldVal)
      }
      // 如果忘记保存了也自动保存上
      // console.log(oldVal, newVal, 'watch')
      this.question = this.questionInfo // 题目信息
      this.radioAnswer = null // 单选题的答案
      this.checkboxAnswer = [] // 多选题的答案
      this.bTypeAnswer = [] // B型题答案
      console.log(this.questionInfo, 'questionInfo')
      // 如果不是B型题
      if (this.questionInfo.questionType) {
        this.questionType = this.questionInfo.questionType // 题目类型
      }
      //  else {
      //   // B型题的情况
      //   this.bTypeAnswer.splice(0, this.bTypeAnswer.length)
      //   for (let i = 0; i < this.question.length; i++) {
      //     this.bTypeAnswer.push('N')
      //   }
      //   this.questionType = this.isB
      // }
      this.questionMarks = this.questionMark // 题目标志
      console.log(this.questionMarks, 'questionMarks')
      this.questionStatus = this.questionInfo.isAnswer // 题目是否做过的状态
      console.log(this.questionStatus, 'questionStatus')
      this.answered() // 如果这道题已经做过,写入答案
      if (this.readOnly) {
        this.judgeAnswer() // 如果这道题已经做过,写入答案
      }
    },
  },
  created() {
    console.log(this.readOnly)
    // console.log(this.question)
    // console.log(this.question)
    // console.log(this.questionMarks)
    // 判断这道题是否已经做过
    this.baseImgUrl = process.env.VUE_APP_BASE_IMG_URL
  },
  mounted() {
    console.log(this.questionInfo, 'questionInfoMounted')
    this.answered() // 如果这道题已经做过,写入答案
    if (this.readOnly) {
      this.judgeAnswer() // 如果这道题已经做过,写入答案
    }
  },
  methods: {
    // 点击修改选项
    handleChange() {
      this.$set(this.questionInfo, 'isLocked', false)
      this.$store.commit('question/SET_QUESTION', this.questionInfo)
    },
    // 点击保存
    handleSave() {
      this.$set(this.questionInfo, 'isLocked', true)
      this.$store.commit('question/SET_QUESTION', this.questionInfo)
    },
    // 判断对错，更新result
    judgeAnswer() {
      if (this.questionType === this.isB) {
        console.log(this.question)
        const trueAnswer_temp = []
        for (const item in this.question) {
          trueAnswer_temp.push(this.LETTER[this.question[item].answer.find((item) => item.isTrue != null).id])
        }
        this.trueAnswer = trueAnswer_temp.join('、')
      } else if (this.questionType === this.isX) {
        const trueAnswer_temp = []
        if (!this.checkboxAnswer.length) return false
        const trueNum = this.question.answer.reduce((temp, newVal, index) => {
          let num = temp
          if (newVal.isTrue) {
            ++num
            trueAnswer_temp.push(newVal.answer.substring(0, 1))
          }
          return num
        }, 0)
        this.trueAnswer = trueAnswer_temp.join('、')
        if (this.checkboxAnswer.length < trueNum) {
          this.result = false
        } else {
          this.result = this.checkboxAnswer.every((item) => item.isTrue)
        }
      } else if (this.questionType !== this.isX) {
        console.log(this.radioAnswer)
        this.result = this.questionMarks.correct
        this.trueAnswer = this.question.answer.find((item) => item.isTrue).answer.substring(0, 1)
      }
    },
    // 如果这道题已经做过,写入答案
    answered() {
      console.log(this.questionMark, 'questionMark')
      console.log(this.questionMark.answer, 'questionMarkAnswer')
      if (this.questionMarks.answer === 'N') return
      // 如果是B型题
      // if (this.questionType === this.isB) {
      //   this.bTypeAnswer = this.questionMarks.answer.split(',')
      // }
      // 判断题目类型,2表示是多选题
      if (this.questionType === 2) {
        const answerIdList = this.questionMarks.answer.split(',')
        this.checkboxAnswer = this.question.answer
        this.checkboxAnswer = this.checkboxAnswer.filter((item) => answerIdList.includes(item.id + ''))
        console.log(this.checkboxAnswer, 'answer')
      } else {
        this.radioAnswer = this.questionMarks.answer
        this.radioAnswer = this.question.answer.find((item) => item.id === parseInt(this.radioAnswer))
      }
    },
    // 选择答案
    changeAnswer() {
      console.log('answer')
      let hasAnswer = false // 是否已答
      let answerId = null // 已答的id
      let correct = false // 是否答对
      console.log(this.checkboxAnswer, 'checkboxAnswer')
      console.log(this.questionType, 'questionType')
      console.log(this.isX, 'isX')
      // 判断是否为X类型的题目，X类型的题目为多选题
      if (this.questionType === this.isX) {
        // 判断是否一个都没有选
        // if (this.checkboxAnswer.length < 1) return
        hasAnswer = this.checkboxAnswer.length > 0
        console.log(hasAnswer, 'hasAnswer')
        if (!hasAnswer) {
          this.questionInfo.isAnswer = false
          return
        }
        // console.log(this.checkboxAnswer, 'checkboxAnswer')

        answerId = this.checkboxAnswer.map((item) => item.id).join(',')
        // console.log(hasAnswer, answerId, 'hasAnswer', 'answerId')
        console.log(this.question, 'question')
        const trueNum = this.question.answer.reduce((temp, item, index) => {
          if (item.isTrue) {
            ++temp
          }
          return temp
        }, 0)
        console.log(trueNum, 'trueNum')
        if (this.checkboxAnswer.length < trueNum) {
          correct = false
        } else {
          correct = this.checkboxAnswer.every((item) => item.isTrue)
        }
        this.questionInfo.isAnswer = true
      } else {
        // 这部分是单选题目
        console.log(this.radioAnswer, 'radioAnswer')
        if (this.radioAnswer === null) return
        hasAnswer = this.radioAnswer
        answerId = this.radioAnswer.id + ''
        correct = Boolean(this.radioAnswer.isTrue)
        this.questionInfo.isAnswer = true
      }
      this.$emit('change', {
        hasAnswer,
        answerId,
        correct,
      })
    },
    // 选择B型题答案
    selectAnswer(questionIndex, answerIndex) {
      if (this.bTypeAnswer.length === 0) {
        for (let i = 0; i < this.question.length; i++) {
          this.bTypeAnswer.push('N')
        }
      }
      this.bTypeAnswer.splice(questionIndex, 1, answerIndex + '')
      const hasAnswer = this.bTypeAnswer.every((item) => item !== 'N')
      const answerId = this.bTypeAnswer.join(',')

      let correct = []
      console.log(this.bTypeAnswer)
      for (const i in this.question) {
        if (this.bTypeAnswer[i] !== 'N') {
          correct[i] = Boolean(this.question[i].answer[parseInt(this.bTypeAnswer[i])].isTrue)
        } else {
          correct[i] = false
        }
      }
      correct = correct.join(',')
      this.$emit('change', {
        hasAnswer,
        answerId,
        correct,
      })
    },

    // 显示解析
    showAnalysis() {
      this.analysisVisible = !this.analysisVisible
    },
  },
}
</script>
<style lang="scss" scoped>
// 题目容器
.questionInfo-container {
  width: 100%;
  height: 100%;
  padding: 30px 15px 0px;
  // 题目类型信息
  .question-info {
    margin-bottom: 20px;
  }
  // 题目问题
  .question-title {
    font-size: 16px;
    color: #333333;
    margin-bottom: 5px;
  }
  // 题目材料
  .question-materials {
    .materials-images {
      max-width: 200px;
      margin: 5px 0px 0px 20px;
      cursor: pointer;
    }
  }
  // 题目答案
  .question-answers {
    .answer-item {
      display: flex;
      width: 100%;
      padding: 10px 0px 0px;
      .answer-content {
        display: inline-block;
        .answer-img {
          width: 100px;
          font-size: 12px;
          color: #c0c4cc;
          vertical-align: bottom;
          margin-bottom: 5px;
        }
        img {
          width: 100%;
        }
      }
    }
    // 覆盖el单选多选文字换行方式
    ::v-deep .el-radio,
    ::v-deep .el-checkbox {
      white-space: normal !important;
    }
    // 覆盖el单选多选禁用时字体颜色
    ::v-deep .is-disabled[class~='answer-item'] {
      .answer-text {
        color: #606266;
      }
    }
    // 高亮正确/错误的答案
    .isRight[class~='is-checked'] {
      .answer-text {
        color: #67c23a;
      }
    }
    .isWrong[class~='is-checked'] {
      .answer-text {
        color: #f56c6c;
      }
    }
  }
  // B型题的样式
  .is-b {
    .single-question {
      display: flex;
      justify-content: flex-start;
      flex-wrap: wrap;
      .question-title {
        flex: 1;
        min-height: 20px;
        margin: 5px 10px 5px 0px;
      }
      .question-options {
        display: inline-block;
        height: 20px;
        width: 20px;
        font-size: 14px;
        line-height: 20px;
        text-align: center;
        color: #409eff;
        border: 1px solid #d9ecff;
        border-radius: 50%;
        margin: 0px 5px;
        background-color: #ecf5ff;
        cursor: pointer;
      }
      .is-select {
        color: #ffffff;
        border: 1px solid #409eff;
        background-color: #409eff;
      }
    }
    .answer-options {
      border-color: red;
      font-size: 14px;
      color: #606266;
      padding-top: 10px;
    }
  }

  // 查看解析 & 确认答案按钮
  .btns {
    height: 40px;
    line-height: 40px;
    padding-top: 10px;
    .result {
      display: inline-block;
      font-size: 15px;
      .analysis-btn {
        margin-left: 15px;
        cursor: pointer;
        color: rgb(78, 110, 242);
      }
      .analysis-btn:hover {
        text-decoration: underline;
      }
    }
  }

  .noAnswer {
    margin: 8px 24px 0px;
    font-size: 15px;
    color: #f56c6c;
  }
  // 显示答案 & 解析
  .show-answer {
    // min-height: 30px;
    font-size: 14px;
    color: #606266;
    border-top: 1px dashed #c0c4cc;
    margin-top: 15px;
    padding-top: 10px;
    .true-answer {
      padding-bottom: 10px;
      margin-bottom: 10px;
      line-height: 18px;
      border-bottom: 1px dashed #c0c4cc;
    }
  }
  .analysis {
    margin: 20px 0px;
  }
}
.statusBox {
  position: absolute;
  top: 660px;
}
</style>
